<template>
  <div class="app-container">
    <!-- 搜索表单保持不变 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
            v-model="queryParams.doctorName"
            placeholder="请输入医生姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属机构" prop="hospitalId">
        <el-select
            v-model="queryParams.hospitalId"
            placeholder="请选择所属机构"
            clearable
            filterable
            style="width: 200px"
        >
          <el-option
              v-for="hospital in hospitalOptions"
              :key="hospital.hospitalId"
              :label="hospital.hospitalName"
              :value="hospital.hospitalId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格操作按钮保持不变 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['medical:doctor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['medical:doctor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['medical:doctor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['medical:doctor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格保持不变 -->
    <el-table v-loading="loading" :data="doctorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="医生头像" align="center" prop="avatar">
        <template #default="scope">
          <el-image
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
          />
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" prop="hospitalName" />
      <el-table-column label="所属科室" align="center" prop="departmentName" />
      <el-table-column label="职称" align="center" prop="title" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '正常' : scope.row.status === '1' ? '停诊' : '--' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['medical:doctor:query']"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['medical:doctor:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['medical:doctor:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 详情弹窗 -->
    <el-dialog title="医生详情" v-model="detailOpen" width="700px" append-to-body>
      <div v-loading="detailLoading" class="doctor-detail-dialog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="医生姓名">{{ detailForm.doctorName || '--' }}</el-descriptions-item>
          <el-descriptions-item label="职称">{{ detailForm.title || '--' }}</el-descriptions-item>
          <el-descriptions-item label="所属机构">{{ detailForm.hospitalName || '--' }}</el-descriptions-item>
          <!-- 修改：显示层级科室名称 -->
          <el-descriptions-item label="所属科室">
            <span class="department-path">{{ getDepartmentDisplayName(detailForm) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="工作年限">
            {{ detailForm.workYears ? detailForm.workYears + '年' : '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="是否名医">
            {{ detailForm.isFamous === 1 ? '是' : detailForm.isFamous === 0 ? '否' : '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="咨询费用">
            {{ detailForm.consultationFee ? '¥' + detailForm.consultationFee : '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailForm.status === '0' ? 'success' : 'danger'">
              {{ detailForm.status === '0' ? '正常' : detailForm.status === '1' ? '停诊' : '--' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="医生头像" :span="2">
            <el-image
                v-if="detailForm.avatar"
                :src="detailForm.avatar"
                style="width: 100px; height: 100px; border-radius: 4px;"
                fit="cover"
            />
            <span v-else>--</span>
          </el-descriptions-item>
          <el-descriptions-item label="擅长领域" :span="2">
            <div class="detail-text-content">{{ detailForm.specialty || '--' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="医生简介" :span="2">
            <div class="detail-text-content">{{ detailForm.description || '--' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Doctor">
import { listDoctor, getDoctor, delDoctor } from "@/api/medical/doctor"
import { listHospital } from "@/api/institution/hospital"
import { listDepartments } from "@/api/department/departments"
import { getHospitalWithDepartments } from "@/api/institution/hospital"
import { useRouter } from 'vue-router'
import { View, Edit, Delete } from '@element-plus/icons-vue'
import { listSchedule } from "@/api/scheduling/schedule"

const { proxy } = getCurrentInstance()
const router = useRouter()

const doctorList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)

// 详情弹窗相关变量
const detailOpen = ref(false)
const detailLoading = ref(false)
const detailForm = ref({})

// 下拉框选项
const hospitalOptions = ref([])
const departmentOptions = ref([])
const allDepartments = ref([]) // 所有科室数据

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    doctorName: null,
    hospitalId: null,
    departmentId: null,
  }
})

const { queryParams } = toRefs(data)

/** 查询医生管理列表 */
function getList() {
  loading.value = true
  listDoctor(queryParams.value).then(response => {
    doctorList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 刷新列表数据 */
function refreshList() {
  // 重置到第一页并重新加载
  queryParams.value.pageNum = 1
  getList()
}

/** 监听存储事件，用于跨页面通信 */
function setupStorageListener() {
  window.addEventListener('storage', (event) => {
    if (event.key === 'doctorListShouldRefresh') {
      refreshList()
      // 清除标记
      localStorage.removeItem('doctorListShouldRefresh')
    }
  })
}

/** 获取机构列表 */
function getHospitalList() {
  listHospital({ pageSize: 1000 }).then(response => {
    hospitalOptions.value = response.rows
  })
}

/** 获取所有科室数据 */
function getAllDepartments() {
  return new Promise((resolve, reject) => {
    listDepartments({ pageSize: 10000 }).then(response => {
      allDepartments.value = response.rows || []
      resolve(allDepartments.value)
    }).catch(error => {
      console.error('获取科室数据失败:', error)
      allDepartments.value = []
      reject(error)
    })
  })
}

/** 获取科室列表 - 根据机构ID获取该机构的科室 */
function getDepartmentList(hospitalId) {
  if (!hospitalId) {
    departmentOptions.value = []
    return
  }

  getHospitalWithDepartments(hospitalId).then(response => {
    if (response.code === 200 && response.data && response.data.departments) {
      departmentOptions.value = response.data.departments
    } else {
      departmentOptions.value = []
    }
  }).catch(error => {
    console.error('获取机构科室失败:', error)
    departmentOptions.value = []
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.doctorId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/medical/doctor/edit')
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _doctorId = row.doctorId || ids.value[0]
  router.push(`/medical/doctor/edit?doctorId=${_doctorId}`)
}

/** 查看详情操作 */
function handleDetail(row) {
  const _doctorId = row.doctorId
  showDetailInDialog(_doctorId)
}

/** 弹窗方式显示详情 */
function showDetailInDialog(doctorId) {
  detailOpen.value = true
  detailLoading.value = true
  detailForm.value = {}

  getDoctor(doctorId).then(response => {
    detailForm.value = response.data
    detailLoading.value = false
  }).catch(() => {
    detailLoading.value = false
    proxy.$modal.msgError('获取医生详情失败')
  })
}

/** 获取科室显示名称（用于详情页面） */
function getDepartmentDisplayName(doctor) {
  if (!doctor || !doctor.departmentId) return '--'

  if (doctor.departmentName && doctor.departmentName.includes('>')) {
    return doctor.departmentName
  }

  const department = allDepartments.value.find(dept => {
    return dept.departmentId === doctor.departmentId ||
        dept.departmentId === doctor.departmentId?.toString()
  })
  if (!department) return doctor.departmentName || '--'

  if ((department.level === 2 || department.level === '2') && department.parentId) {
    const parentDept = allDepartments.value.find(dept => {
      return dept.departmentId === department.parentId ||
          dept.departmentId === department.parentId?.toString()
    })
    if (parentDept) {
      return `${parentDept.departmentName}>${department.departmentName}`
    }
  }

  return department.departmentName || '--'
}

/** 删除按钮操作 - 检查排班绑定 */
async function handleDelete(row) {
  const _doctorId = row.doctorId || ids.value[0]

  try {
    // 检查该医生是否绑定了排班
    const scheduleResponse = await listSchedule({
      doctorId: _doctorId,
      pageSize: 1,
      pageNum: 1
    })

    if (scheduleResponse.total > 0) {
      proxy.$modal.msgError(`该医生已绑定 ${scheduleResponse.total} 个排班，无法删除`)
      return
    }

    // 确认删除
    await proxy.$modal.confirm('是否确认删除医生编号为"' + _doctorId + '"的数据项？')

    // 执行删除
    await delDoctor(_doctorId)
    getList()
    proxy.$modal.msgSuccess("删除成功")
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      proxy.$modal.msgError("删除失败")
    }
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('medical/doctor/export', {
    ...queryParams.value
  }, `doctor_${new Date().getTime()}.xlsx`)
}

// 页面激活时检查是否需要刷新
onActivated(() => {
  // 检查是否有刷新标记
  if (localStorage.getItem('doctorListShouldRefresh')) {
    refreshList()
    localStorage.removeItem('doctorListShouldRefresh')
  }
})

// 初始化加载列表和数据
onMounted(() => {
  getList()
  getHospitalList()
  getAllDepartments()
  setupStorageListener()
})
</script>

<style scoped>
.detail-text-content {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  line-height: 1.6;
  white-space: pre-wrap;
  min-height: 60px;
}

.doctor-detail-dialog {
  min-height: 400px;
}

.department-path {
  font-weight: 500;
  color: #409eff;
}

/* 操作按钮样式 */
:deep(.el-button--small) {
  padding: 5px;
  margin: 0 2px;
}

:deep(.small-padding .cell) {
  padding: 0 5px;
}
</style>